// pages/launchContract/launchContract.js
// const wxbarcode = require('../../component/wxbarcode/index.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    options: [{
      name: '优选签约'
    }, {
      name: '放盘签约'
    }, {
      name: '折扣签约'
    }],
    defaultOption: {
      name: '优选签约'
    },
    selected: {},
    currentId: null,
    show: false,
    showcode: false,
    typeShow: true,
    select: {},
    showHome: false,
    type: '优选签约',
    remind: [{
        id: 1,
        orderid: "3248956565f5656",
        fangyuanTag: 1,
        favprice: 75,
        oriprice: 180,
        address: '广州市番禺区石岗路地址地址地址地址地址',
        time: '2020/09/06-2020/09/28',
        tabs: ["4.1折", "491.23㎡", "变卖"]
      },
      {
        id: 2,
        orderid: "32fafa489565655656",
        fangyuanTag: 2,
        favprice: 105,
        oriprice: 280,
        address: '广州市番禺区石岗路地址地址地址',
        time: '2020/09/09-2020/09/24',
        tabs: ["2.7折", "114.23㎡", "变卖"]
      }
    ],
    fp: [],
    zk: [],
    user: {},
    page_token: 0
  },

  async showclick() {
    let that = this;
    this.setData({
      show: true
    })
    var status = null;
    var orderType = null;
    var obj = {};
    switch (that.data.type) {
      case '优选签约':
        status = 1;
        orderType = '优选';
        obj.foreclosed_house_id = that.data.select.id
        await getApp().ports.fpljqy({
          data: obj
        }).then(async (res) => {
          var res = res.data;
          that.select = res.foreclosed_house
          // that.setData({
          //   select: res.foreclosed_house,
          // })
        }).catch(() => {
          console.error('出啥错了？');
        });
        break;
      case '折扣签约':
        status = 2;
        orderType = '折扣';
        obj.discount_house_bookingorder_id = that.data.select.id
        await getApp().ports.api5({
          data: obj
        }).then(async (res) => {
          var res = res.data;
          that.data.select = res
          // that.setData({
          //   select: res.discount_house
          // })
        }).catch(() => {
          console.error('出啥错了？');
        });
        break;
      case '放盘签约':
        status = 3
        orderType = '折扣'
        await getApp().ports.cjfp({
          data: {}
        }).then(async (res) => {
          var res = res.data;
          that.data.select = res
          console.log(that.data.select)
        }).catch(() => {
          console.error('出啥错了？');
        });
        break;
    }
    let json = {
      category: 'getwxacodeunlimit'
    } //有个数限制
    console.log(that.data.select)
    var select = that.data.select;
    console.log(select)
    let inviId = select.id //房源签约id
    let type = status //订单类型  1优选、2折扣、3放盘
    let userid = wx.getStorageSync('userId') //用户id、绑定当前用户
    // let housetype = orderType //房源类型1优选、2折扣
    let data = {
      appid: getApp().globalData.appid, //小程序id
      path: "pages/index/index", //扫码进入那个页面
      params: JSON.stringify({
        id: inviId,
        type: type,
        userId: userid,
        // housetype: housetype
      }) //房源id、房源类型、订单类型、用户id
    }
    getApp().ports.apiqrcode({
      data,
      json
    }).then((res) => {
      // console.log(res)
      // let base64 = wx.arrayBufferToBase64(res.data)
      that.setData({
        imgurl: 'data:image/png;base64,' + res.data
      })
    }).catch(() => {
      console.error('生成二维码错误！')
    })
  },
  getUserInfo(event) {
    console.log(event.detail);
  },
  onClose1() {
    this.setData({
      close: false
    });
  },

  onShowClose() {
    this.setData({
      show: false
    })
  },


  onShareAppMessage: function () {
    let that = this;
    var select = that.data.select;
    var orderType = that.data.orderType;
    var sharehouseId = select.id; //房源id
    let type = select.type //订单类型  1优选、2折扣、3放盘
    let shareId = wx.getStorageSync('userId') //当前id/用于绑定
    let housetype = orderType || select.type //房源类型1优选、2折扣
    console.log(sharehouseId, type, userid, housetype)
    return {
      title: '去邀请更多小伙伴一起看房吧',
      path: 'pages/index/index?share=' + shareId,
      success: function (res) {
        console.log(res)
      }
    }
  },
  searchInput(e){
    var that = this;
    that.setData({
      key: e.detail
    })
  },
  search(e) {
    var that = this;
    var type = that.data.type;
    var data = {
      page_size: 10,
      page_token: 0,
    }
    that.api(data)
    // if (data.key) {
    //   switch (type) {
    //     case '优选签约':
    //       getApp().ports.api1({
    //         data
    //       }).then((res) => {
    //         var res = res.data;
    //         for (var i = 0; i < res.results.length; i++) {
    //           res.results[i].url = "../details/details?status=0&&id=" + res.results[i].id
    //           res.results[i].tags = [{
    //             name: res.results[i].built_up_area_square_centimeter + '㎡'
    //           }, {
    //             name: res.results[i].discount_rate + '折'
    //           }, {
    //             name: res.results[i].stage
    //           }]
    //           if (res.results[i].residential_quarter_name) res.results[i].title = res.results[i].residential_quarter_name + res.results[i].title
    //           res.results[i].market_price_yuan = Math.floor((res.results[i].market_price_yuan / 10000));
    //           res.results[i].price_yuan = Math.floor((res.results[i].price_yuan / 10000));
    //           res.results[i].deal_price = Math.floor((res.results[i].deal_price / 10000));
    //         }
    //         that.setData({
    //           fp: res
    //         })
    //       }).catch(() => {
    //         console.error('出啥错了？');
    //       });
    //       break;
    //     case '折扣签约':
    //       getApp().ports.api5({
    //         data
    //       }).then((res) => {
    //         var res = res.data;
    //         for (var i = 0; i < res.results.length; i++) {
    //           res.results[i].status = statuss[res.results[i].status]
    //           res.results[i].url = "../details/details?status=1&&id=" + res.results[i].id
    //         }
    //         that.setData({
    //           zk: res
    //         })
    //       }).catch(() => {
    //         console.error('出啥错了？');
    //       });
    //       break;
    //   }
    // } else {
    //   that.api({})
    // }
    console.log(that.data.type)
  },
  getInfo(e) {
    var that = this;
    console.log(e);
    var id = e.detail.dataset.id
    var index = e.detail.dataset.index
    var data = {
      // id: e.detail
    }
    console.log()
    var type = that.data.type;
    console.log(type)
    switch (type) {
      case '优选签约':
        that.setData({
          select: that.data.fp.results[index],
          currentId: id
        })
        break;
      case '折扣签约':
        that.setData({
          select: that.data.zk.results[index],
          currentId: id
        })
        break;
    }
    that.onClose()
  },
  api(data) {
    var that = this;
    var type = that.data.type;
    if(that.data.key) data.key = that.data.key
    switch (type) {
      case '折扣签约':
        data.status = 2
        getApp().ports.api5({
          data: data
        }).then((res) => {
          var res = res.data;
          if (that.data.Loading != '') {
            wx.hideLoading({
              success: (res) => {},
            })
          }
          if (data.page_token >= 1) {
            for (var j = 0; j < res.results.length; j++) {
              res.results[j].time = res.results[j].upload_time
              that.data.zk.results.push(res.results[j])
            }
            for (var j = 0; j < res.results.length; j++) {
              that.data.zk.results.push(res.results[j])
            }
            res.results = that.data.zk.results
          } else {
            for (var i = 0; i < res.results.length; i++) {
              res.results[i].time = res.results[i].upload_time
            }
          }
          console.log(res.results)
          that.setData({
            zk: res
          })
        }).catch(() => {
          console.error('出啥错了？');
        });
        break;
      case '优选签约':
        getApp().ports.api1({
          data: data
        }).then((res) => {
          var res = res.data;
          if (that.data.Loading != '') {
            wx.hideLoading({
              success: (res) => {},
            })
          }
          if (data.page_token >= 1) {
            for (var i = 0; i < res.results.length; i++) {
              // res.results[i].url = "../details/details?status=0&&id=" + res.results[i].id
              res.results[i].tags = [{
                name: res.results[i].built_up_area_square_centimeter + '㎡'
              }, {
                name: res.results[i].discount_rate + '折'
              }, {
                name: res.results[i].stage
              }]
              res.results[i].market_price_yuan = Math.floor((res.results[i].market_price_yuan / 10000));
              res.results[i].price_yuan = Math.floor((res.results[i].price_yuan / 10000));
              res.results[i].deal_price = Math.floor((res.results[i].deal_price / 10000));
              if (res.results[i].residential_quarter_name) res.results[i].title = res.results[i].residential_quarter_name + res.results[i].title
              res.results[i].time = res.results[i].start_time + '-' + res.results[i].end_time
            }
            for (var j = 0; j < res.results.length; j++) {
              that.data.fp.results.push(res.results[j])
            }
            res.results = that.data.fp.results
          } else {
            for (var i = 0; i < res.results.length; i++) {
              // res.results[i].url = "../details/details?status=0&&id=" + res.results[i].id
              res.results[i].tags = [{
                name: res.results[i].built_up_area_square_centimeter + '㎡'
              }, {
                name: res.results[i].discount_rate + '折'
              }, {
                name: res.results[i].stage
              }]
              if (res.results[i].residential_quarter_name) res.results[i].title = res.results[i].residential_quarter_name + res.results[i].title
              res.results[i].market_price_yuan = Math.floor((res.results[i].market_price_yuan / 10000));
              res.results[i].deal_price = Math.floor((res.results[i].deal_price / 10000));
              res.results[i].price_yuan = Math.floor((res.results[i].price_yuan / 10000));
              res.results[i].time = res.results[i].start_time + '-' + res.results[i].end_time
            }
          }
          that.setData({
            fp: res
          })
        }).catch(() => {
          console.error('出啥错了？');
        });
        break;

    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // wxbarcode.qrcode('GoodCode', '1234567890123456789', 300, 300);
    var data = {}
    that.api(data);
    console.log(wx.getStorageSync('userId'))
    var id = wx.getStorageSync('userId')
    getApp().ports.yhxx({
      id
    }).then((res) => {
      var res = res.data;
      console.log(res);
      var user = {
        img: res.avatar_url,
        name: res.nickname,
        phone: res.phone
      }
      that.setData({
        user: user
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // 选择房源弹出层
  Popup() {
    this.api({});
    this.setData({
      showHome: true
    });
  },
  onClose() {
    this.setData({
      showHome: false
    });
  },
  // 分享弹出层
  share() {
    this.setData({
      showcode: true
    });
  },
  onCloseCode() {
    this.setData({
      showcode: false
    });
  },
  change(e) {
    var that = this;
    console.log(e)
    that.setData({
      type: e.detail.name
    })
    var i = e.detail.name;
    if (i == '放盘签约') {
      that.setData({
        typeShow: false
      });
    } else {
      that.setData({
        typeShow: true
      });
    }
  },
  eventSave() {
    var that = this;
    wx.getFileSystemManager().writeFile({
      filePath: wx.env.USER_DATA_PATH + '/wawa.png', //创建一个临时文件名
      data: that.data.imgurl.slice(22), //写入的文本或二进制数据
      encoding: 'base64', //写入当前文件的字符编码
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/wawa.png',
          success: function (res) {
            wx.showToast({
              title: '保存图片成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function (err) {
            console.log(err)
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  showToast() {
    wx.showToast({
      title: '请先选择房源',
      icon: 'none',
      duration: 2000
    })
  },
  scrollend() {
    var that = this;
    var type = [that.data.fp, that.data.zk];
    var active = (that.data.type == '优选签约' ? 0 : 1)
    // var myl = ['fpmyl', 'zkmyl'];
    //检查是否还有数据可以加载
    var total_size = type[active].total_size;
    var size = type[active].results.length;
    var page_token = that.data.page_token += 1
    console.log(size, '========================', total_size, 'list==', that.data.yy)
    //如果还有，则继续加载
    if (total_size > size) {
      var data = {
        page_size: 10,
        page_token: page_token
      }
      that.data.Loading = wx.showLoading({
        title: '加载中',
      })
      that.api(data)
      // console.log(size,data)
      //如果没有了，则停止加载，显示没有更多内容了
    } else {
      console.log('没有啦')
      var myls = myl[active]
      that.setData({
        [myls]: true,
      })
    }
    that.setData({
      Loading: that.data.Loading,
      page_token: page_token
    })
  }
})